<template>
  <view class="page">
    <view class="tabs">
      <u-tabs activeStyle="color:#ea4679;fontWeight:bold;fontSize:32rpx;"
              @change="tabsChange"
              :current="tabsCurrent" lineColor="#ea4679"
              :list="tabsList" :scrollable="false"></u-tabs>
    </view>

    <scroll-view class="main" :scroll-x="false" :scroll-y="true" :scroll-with-animation="true">
      <view class="box-pay">
        <view class="box" v-if="goodsList && goodsList.length > 0">
          <view class="box-title">
            <view class="line"></view>
            <text>选择套餐</text>
          </view>
          <view class="goods-list">
            <view class="goods" :class="{active: index === activeIndex}" v-for="(item, index) in goodsList" @tap="chooseGoods(index)">
              <view class="hint" v-if="item.hint">{{ item.hint }}</view>
              <view class="title">
                <text class="num">{{ item.num }}</text>
                <text class="unit" v-if="type === 'point'">{{ userInfo.point_title || '算力' }}</text>
                <text class="unit" v-if="type === 'body'">点</text>
                <text class="unit" v-if="type === 'voice'">点</text>
              </view>
              <view class="price">特价<text>{{ item.price / 100 }}</text>元</view>
              <view class="market_price" v-if="item.market_price > 0">原价{{ item.market_price / 100 }}元</view>
            </view>
            <view style="clear: both;"></view>
          </view>
        </view>
        <view class="box" v-if="goodsList && goodsList[activeIndex] && goodsList[activeIndex].desc && goodsList[activeIndex].desc.length > 0" style="padding-top: 0;">
          <view class="box-title">
            <view class="line"></view>
            <text>套餐权益</text>
          </view>
          <view class="desc-list">
            <view class="desc-item" v-for="item in goodsList[activeIndex].desc">
              <view class="icon">
                <image src="/static/pay/ic_checked.png"></image>
              </view>
              <view class="text">{{ item }}</view>
            </view>
            <view style="clear: both;"></view>
          </view>
        </view>
      </view>

      <!-- </block> -->
    </scroll-view>

    <view class="paynow">
      <button class="btn-pay" @tap="doPay">立即支付</button>
      <view class="agreement">
        <label>
          <checkbox-group @change="agreeChange" style="display: flex; align-items: center;">
            <checkbox class="check" value="1" :checked="is_agree" color="#ea4679"/>
            已阅读并同意
          </checkbox-group>
        </label>
        <view>
          <text @tap="toArticle('agree_pay')">《充值协议》</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
const app = getApp();
export default {
  data() {
    return {
      type: 'point',
      goods_id: 0,
      goodsList: [],
      activeIndex: -1,
      userInfo: {
        user_id: 0,
        nickname: '',
        avatar: '',
        balance: 0,
        balance_body: 0,
        balance_voice: 0,
        point_title: ''
      },
      openid: '',
      tabsList: [
        {
          name: '',
          type: 'point'
        },
        {
          name: '形象克隆',
          type: 'body'
        },
        {
          name: '声音克隆',
          type: 'voice'
        }
      ],
      tabsCurrent: 0,
      paying: false,
      is_agree: false
    };
  },
  onLoad(options) {
    const isAgree = uni.getStorageSync('payAgree')
    this.type = options.type ? options.type : 'point'
    this.is_agree = !!isAgree

    this.getUserInfo();
    this.getGoodsList();
    // #ifdef MP-WEIXIN
    this.getWxappOpenid();
    // #endif
  },
  methods: {
    getGoodsList() {
      this.$util.request({
        url: '/pay/getPackageList',
        data: {
          type: this.type
        }
      }).then((res) => {
        const goodsList = res.data;
        if (goodsList.length > 0) {
          this.activeIndex = 0
          goodsList.forEach((item, index) => {
            if (item.is_default) {
              this.activeIndex = index
            }
          });
          this.goodsList = goodsList
        }
      });
    },
    getWxappOpenid() {
      const that = this
      wx.login({
        success: function (e) {
          var code = e.code
          that.$util.request({
              url: '/wxapp/getOpenid',
              data: {
                code: code
              }
            }).then(res => {
              that.openid = res.data.openid;
            })
        },
        fail: function (e) {
          console.log(e);
        }
      });
    },
    getUserInfo() {
      this.$util.request({
        url: '/user/getInfo'
      }).then(res => {
        this.userInfo = res.data
        this.tabsList[0].name = res.data.point_title || '算力'
      })
    },
    chooseGoods(index) {
      this.activeIndex = index
    },
    tabsChange(val) {
      this.tabsCurrent = val.index;
      this.type = this.tabsList[val.index].type
      this.goodsList = []
      this.activeIndex = -1
      this.getGoodsList()
    },
    doPay() {
      var that = this;
      if (this.paying) {
        return false;
      }
      const activeIndex = this.activeIndex
      if (activeIndex === -1 || !this.goodsList[activeIndex].id) {
        this.$util.message('请选择套餐');
        return false;
      }
      if (!this.is_agree) {
        this.$util.message('请阅读并同意《充值协议》');
        return false;
      }

      this.paying = true
      setTimeout(() => {
        this.paying = false
      }, 2000);

      var platform = 'wxapp'
      // #ifdef WEB
      platform = 'h5'
      // #endif
      this.$util.request({
        url: '/pay/createOrder',
        data: {
          platform: platform,
          trade_type: 'jsapi',
          type: this.type,
          package_id: this.goodsList[activeIndex].id,
          openid: this.openid
        }
      }).then((res) => {
        var paySuccess = function () {
          that.$util.message('支付成功', 'error', function () {
            uni.redirectTo({
              url: '/pages/my/my'
            });
          });
        };
        var payFail = function (res) {
          if (res.errMsg.indexOf('cancel') === -1) {
            that.$util.message('发起支付失败：' + res.errMsg);
          }
        };

        var trade_type = res.data.trade_type;
        if (trade_type === 'jsapi') {
          const jssdk = res.data.jssdk;
          const orderInfo = res.data.orderInfo;
          uni.requestPayment({
            provider: 'wxpay',
            orderInfo: {
              appid: orderInfo.appid,
              mch_id: orderInfo.mch_id,
              nonce_str: orderInfo.nonce_str,
              prepay_id: orderInfo.prepay_id,
              sign: orderInfo.sign
            },
            timeStamp: jssdk.timestamp,
            nonceStr: jssdk.nonceStr,
            package: jssdk.package,
            signType: jssdk.signType,
            paySign: jssdk.paySign,
            success: paySuccess,
            fail: payFail
          })
        } else if (trade_type === 'native') {
          uni.navigateTo({
            url: '/pages/pay/qrcode?total_fee=' + res.data.total_fee + '&order_id=' + res.data.order_id + '&pay_url=' + encodeURIComponent(res.data.pay_url)
          })
        } else if (trade_type === 'h5') {
          window.location.href = res.data.pay_url
        }

      });
    },
    agreeChange(e) {
      let value = e.detail.value
      let isAgree = value.length > 0
      if (isAgree) {
        uni.setStorageSync('payAgree', isAgree)
      } else {
        uni.removeStorageSync('payAgree')
      }
      this.is_agree = isAgree
    },
    toArticle(type) {
      uni.navigateTo({
        url: '/pages/article/detail?type=' + type
      })
    }
  }
};
</script>
<style scoped>
@import './pay.css';
</style>

